package net.zoneland.greenleaf.timer.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import net.zoneland.greenleaf.common.date.DateOperation;
import net.zoneland.greenleaf.common.pagination.Pagination;
import net.zoneland.greenleaf.system.controller.BaseController;
import net.zoneland.greenleaf.timer.entity.Sys_schedulejob;
import net.zoneland.greenleaf.timer.service.Sys_schedulejobServiceI;
import net.zoneland.greenleaf.timer.task.TaskUtils;

/**
 * SYS_SCHEDULEJOB[定时任务信息表]表操作控制层（Controller|Action）

 * 表   名：SYS_SCHEDULEJOBCONTROLLER<br/>
 * 注   释：<br/>
 * 作   者：李义<br/>
 * 日   期：2014-12-19 22:34:18
**/
@Controller
@RequestMapping("sys_schedulejob")
public class Sys_schedulejobController extends BaseController { 

	/**
	 * 如果需要系统对此Controller的访问进行监控，记录服务访问的时间，耗时，那么请将monitor属性设置为“true”
	 */
	public boolean monitor = false; 
	private DateOperation dateOperation = new DateOperation();
	public static Logger logger = Logger.getLogger(Sys_schedulejobController.class);

	//获取类的名称
  	@SuppressWarnings("unused")
	private String clazzName = new Object() {
  		public String getClassName() {
  			String clazzName = this.getClass().getName();
  			return clazzName.substring(0, clazzName.lastIndexOf('$'));
  		}
  	}.getClassName();

	/**
	 * sys_schedulejobService
	 * @param sys_schedulejobService
	**/
	@Autowired
	private Sys_schedulejobServiceI sys_schedulejobService;

	/**
     * 根据ID获取信息数据
     * 
     * @param id
     * @return
     */
    @RequestMapping( method = RequestMethod.GET, value = "/{id}", produces = "text/html;charset=UTF-8" )
    @ResponseBody
    public Object get( @PathVariable("id") String id ){
		Map<String, Object> map = new HashMap<String, Object>();
		Sys_schedulejob entity = null;
		Boolean check = true;
		
		map.put("jobid", id);
		if( id == null || "(0)".equals( id ) || id.isEmpty() ){
			check = false;
			map.put("result", "error");
			map.put("message", "系统获取到的ID不正常，ID:" + id );
		}
		if( check ){
			try {
				entity = sys_schedulejobService.get( map );
			} catch (Exception e) {
				check = false;
				map.put("result", "error");
				map.put("message", "系统根据ID获取对象失败!");
				logger.error("系统根据ID获取对象发生异常。ID:" + id, e);
			}
		}
		if( check ){
			if( entity != null ){
				map.put("result", "success");
				map.put( "data", entity );
			}else{
				map.put("result", "error");
				map.put("message", "数据不存在！ID:" + id );
			}
		}
		return map;
	}

    /**
	 * 获取信息表列表
	 * 返回JSON格式数据
	 * 如果不需要分页，您可以考虑将pagesize设置为足够大的数字，系统默认为20
	 * 
	 * @param Map<String, Object> paramMap 
	**/
	@RequestMapping( method = RequestMethod.POST, value = "/list" )
    @ResponseBody
	public Object list( @RequestBody Map<String, Object> paramMap ) {		
		String page = "1";
		Integer pagesize = 20, totalRecord=0;
		List<Sys_schedulejob> list  = null;
		Map<String, Object> map=new HashMap<String,Object>();
		Pagination<?> pagination = null;
		Boolean check = true;
		
		if( paramMap == null ){
			check = false;
			map.put("result", "error");
			map.put("message", "参数列表为空，无法进行数据查询！");
		}
		if( check ){
			if(paramMap.get("page")!=null){
				page = paramMap.get("page").toString();
			}
			if(paramMap.get("pagesize") != null){
				try{
					pagesize = Integer.parseInt(paramMap.get("pagesize").toString());
				}catch(Exception e){
					pagesize = 20;
				}
			}
			if( paramMap.get("c_codes")   != null && paramMap.get("c_codes").toString().trim().length() > 1){
				paramMap.put("c_codes", paramMap.get("c_codes").toString().trim().split(","));
			}
		}
		if( check ){
			try{
				totalRecord = sys_schedulejobService.getListCount( paramMap );
			}catch( Exception e ){
				check = false;
				map.put("result", "error");
				map.put("message", "系统根据条件查询信息数据条目总数时发生异常！");
				logger.error( e );
			}
		}
		if( check ){
			try{
				pagination = Pagination.newPagination( pagesize, page, totalRecord );
				paramMap.put( "startRow", pagination.getStartRow() );
				paramMap.put( "pageSize", pagesize );
			}catch( Exception e ){
				check = false;
				map.put("result", "error");
				map.put("message", "系统根据条件进行分页信息计算时发生异常！");
				logger.error( e );
			}
		}
		if( check ){		
			if( totalRecord>0 ){
				try{
					list = sys_schedulejobService.getList( paramMap );
				}catch( Exception e ){
					check = false;
					map.put("result", "error");
					map.put("message", "系统根据条件进行信息列表查询信息数据时发生异常！");
					logger.error( e );
				}
			}
		}
		if( check ){
			if( list == null ){
				list = new ArrayList<Sys_schedulejob>();
			}
		}
		if( check ){
			map.put( "result", "success" );
			map.put( "message", "系统查询信息数据成功！" );
			map.put( "pagination", pagination );
			map.put( "data", list );
		}
		return map;
	}
	
	/**
	 * 增加或编辑一个定时任务
	 * 返回JSON格式数据
	 * JOB的NAME和GROUP不允许修改，任务的控制是靠NAME+GROUP去作为一个任务唯一的识别信息的。
	 * 如果定时任务的运行时间被更新，则自动更新正在运行的任务的运行时间
	 * 返回JSON格式数据
	 * 
	 * @param entity
	**/
	@RequestMapping( method = RequestMethod.POST, value = "/save" )
    @ResponseBody
	public Object save( @RequestBody Sys_schedulejob entity ){
		Map<String, Object> map = new HashMap<String, Object>();
		Boolean check = true;
		
		if( entity == null ){
			check = false;
			map.put("result", "error");
			map.put("message", "需要保存的信息数据为空!");
		}
		if( check ){
			map = validate( entity, map );
			if( map.get( "result" ) == null || "error".equalsIgnoreCase( map.get( "result" ).toString() ) ){
				check = false;
			}
		}
		if( check ){
			try{
				entity = sys_schedulejobService.addOrUpdate( entity );
				map.put("result", "success");
				map.put("message", "保存信息成功！");
				map.put( "data", entity );
			}catch(Exception e){
				check = false;
				map.put("result", "error");
				map.put("message", "保存信息数据失败!");
				logger.error("保存信息数据失败", e);
			}
		}
		if( check ){
			if( map.get( "changedCronexpression" ) != null ){
				if( (Boolean)map.get( "changedCronexpression" ) ){
					//更新定时任务运行时间
					try {
						new TaskUtils().updateJobCron( entity );
						logger.debug("save方法更新定时任务["+ entity.getJobname() +"]的运行时间。");
					} catch (SchedulerException e) {
						logger.error("保存信息成功，但更新定时任务运行时间失败", e);
					}
				}
			}
		}
		return map;
	}
	
	/**
	 * 对需要进行保存的对象里的信息校验
	 * @param entity
	 * @param map 
	 * @return
	 */
	private Map<String, Object> validate( Sys_schedulejob entity, Map<String, Object> map ) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		List<Sys_schedulejob> list = null;
		boolean changedCronexpression = false;
		
		paramMap.put("jobid", entity.getJobid());
		
		list  = sys_schedulejobService.getList(paramMap);
		if( list != null && list.size() > 0 ){
			entity.setJobname( list.get(0).getJobname());
			entity.setCreatetime( list.get(0).getCreatetime());
			//判断是否更新了运行时间
			if( !list.get(0).getCronexpression().equals( entity.getCronexpression()) ){
				changedCronexpression = true;
			}
		}else{
			entity.setCreatetime( dateOperation.getNowDateTime() );
		}
		entity.setUpdatetime(dateOperation.getNowDateTime());
		/**
		 * 补全固定的信息
		 */
		entity.setJobgroup("定时任务组");
		entity.setMethodname("execute");
		map.put("result", "success");
		map.put("changedCronexpression", changedCronexpression ); //如果更新了执行时间，那么定时器组里的任务需要更新
		return map;
	}
	
	/**
	 * 根据ID删除一个系统配置信息表信息
	 * 返回JSON格式数据
	 * @param int id
	**/
	@RequestMapping( method = RequestMethod.DELETE, value = "/{id}" )
    @ResponseBody
    public Object deleteById( @PathVariable("id") String id ){
		Map<String, Object> map = new HashMap<String, Object>();
		Sys_schedulejob entity = null;
		Boolean check = true;
		
		map.put("jobid", id);
		if( id == null || id.isEmpty() || "id".equalsIgnoreCase( id )){
			check = false;
			map.put( "result", "error" );
			map.put( "message", "需要删除的信息ID为空!" );
		}

		if( check ){
			try {
				entity = sys_schedulejobService.get(map);
				if( entity == null ){
					check = false;
					map.put("result", "error");
					map.put("message", "需要删除的信息数据不存在失败!ID:" + id );
				}
			} catch (Exception e) {
				check = false;
				map.put("result", "error");
				map.put("message", "根据ID查询需要删除的信息数据失败!ID:" + id );
				logger.error("根据ID查询需要删除的信息数据失败!ID:" + id, e);
			}
		}
		if( check ){
			try {
				sys_schedulejobService.delete( map );
				map.put( "result", "success" );
				map.put( "message", "成功删除一个信息数据！" );
			} catch (Exception e) {
				check = false;
				map.put("result", "error");
				map.put("message", "删除信息数据失败!ID:" + id );
				logger.error("删除信息数据失败!ID:" + id, e);
			}
		}
		if( check ){
			try {
				new TaskUtils().deleteJob( entity );
			} catch (SchedulerException e) {
				logger.error("定时任务信息删除成功，但删除定时器组中的定时任务失败!ID:" + id, e);
			}
		}
		return map;
	}
	
	/**
	 * 根据ID删除多个系统配置信息表信息
	 * 返回JSON格式数据
	 * @param Map<String, Object> paramMap
	**/
	@RequestMapping( method = RequestMethod.POST, value = "/delete/batch" )
    @ResponseBody
	public Object deleteByIds( @RequestBody Map<String, Object> paramMap ){
		Map<String, Object> map = new HashMap<String, Object>();
		List<Sys_schedulejob> list = null;
		String ids_str = null;
		Boolean check = true;
		
		if( paramMap == null || paramMap.get( "ids" ) == null ){
			check = false;
			map.put("result", "error");
			map.put("message", "参数列表为空，无法进行数据删除！");
		}
		if( check ){
			ids_str = (String)paramMap.get( "ids" );
			if( ids_str != null && ids_str.isEmpty() ){
				check = false;
				map.put("result", "error");
				map.put("message", "参数列表中ID列表为空，无法进行数据删除！");
			}else{
				paramMap.put("ids", ids_str.split(",") );
			}
		}
		if( check ){
			try {
				sys_schedulejobService.delete( paramMap );
				map.put("result", "success");
				map.put("message", "成功删除信息数据！");
			} catch (Exception e) {
				map.put( "result", "error");
				map.put( "message", "删除信息数据失败!ID:" + paramMap.get( "ids" ) );
				logger.error( "系统信息数据失败!ID:" + paramMap.get( "ids" ), e );
			}
		}
		if( check ){
			list = sys_schedulejobService.getList( paramMap );
			if( list != null && !list.isEmpty() ){
				for( Sys_schedulejob schedulejob : list ){
					try {
						new TaskUtils().deleteJob( schedulejob );
					} catch (SchedulerException e) {
						logger.error("定时任务信息删除成功，但删除定时器组中的定时任务失败!ID:" + schedulejob.getJobid(), e );
					}
				}
			}
		}
		return map;
	}
	
	/**
	 * 禁用定时任务
	 * 返回JSON格式数据
	 * @param String jsonstring
	**/
	@RequestMapping( method = RequestMethod.GET, value = "/stopJob/{id}" )
    @ResponseBody
    public Object stopJob( @PathVariable("id") String id ){
		Map<String, Object> map=new HashMap<String, Object>(), paramMap = new HashMap<String, Object>();
		Sys_schedulejob sys_schedulejob = null;
		TaskUtils taskUtils = new TaskUtils();
		try{
			paramMap.put("jobid", id );
			List<Sys_schedulejob> list  = sys_schedulejobService.getList(paramMap);
			if( list != null && list.size() > 0 ){
				sys_schedulejob = list.get(0);
				sys_schedulejob.setJobstatus("0");
				sys_schedulejobService.addOrUpdate( sys_schedulejob );
				taskUtils.deleteJob( sys_schedulejob );
				logger.debug("stopJob方法禁用定时任务["+sys_schedulejob.getJobname()+"]成功。");
				map.put("result", "success");
				map.put("message", "成功禁用定时任务！");
				map.put("exception", "");
			}else{
				map.put("result", "error");
				map.put("message", "根据ID=["+id+"]未查询到定时任务信息！");
			}
		}catch(Exception e){
			map.put("result", "error");
			map.put("message", "禁用定时任务失败!");
			map.put("exception", "");
			logger.error("禁用定时任务失败", e);
		}
		return map;
	}
	
	/**
	 * 启用定时任务
	 * 返回JSON格式数据
	 * @param String jsonstring
	**/
	@RequestMapping( method = RequestMethod.GET, value = "/startJob/{id}" )
    @ResponseBody
    public Object startJob( @PathVariable("id") String id ){
		Map<String, Object> map = new HashMap<String, Object>(), paramMap = new HashMap<String, Object>();
		Sys_schedulejob sys_schedulejob = null;
		TaskUtils taskUtils = new TaskUtils();
		try{
			paramMap.put("jobid", id );
			List<Sys_schedulejob> list  = sys_schedulejobService.getList(paramMap);
			if( list != null && list.size() > 0 ){
				sys_schedulejob = list.get(0);
				sys_schedulejob.setJobstatus("1");
				taskUtils.deleteJob( sys_schedulejob );
				sys_schedulejobService.addOrUpdate( sys_schedulejob );
				taskUtils.addJob( sys_schedulejob );
				logger.debug("startJob方法启用定时任务["+sys_schedulejob.getJobname()+"]成功。");
				map.put("result", "success");
				map.put("message", "成功启用定时任务！");
			}else{
				map.put("result", "error");
				map.put("message", "根据ID=["+id+"]未查询到定时任务信息！");
			}
		}catch(Exception e){
			map.put("result", "error");
			map.put("message", "禁用定时任务失败!");
			logger.error("stopJob方法启用定时任务失败", e);
		}
		return map;
	}
	/**
	 * 根据ID暂停一个定时任务
	 * 返回JSON格式数据
	 * @param int id
	**/
	@RequestMapping( method = RequestMethod.GET, value = "/pauseJob/{id}" )
    @ResponseBody
    public Object pauseJob( @PathVariable("id") String id ){
		Sys_schedulejob schedulejob = null;
		Map<String, Object> map = new HashMap<String, Object>(), paramMap = new HashMap<String, Object>();
		try {
			TaskUtils taskUtils = new TaskUtils();
			 //先查询出需要操作的JOB对象			
			paramMap.put("jobid", id);
			schedulejob = sys_schedulejobService.get(paramMap);
			if( schedulejob != null ){
				taskUtils.pauseJob( schedulejob );
				logger.debug("pauseJob方法定时任务：["+schedulejob.getJobname()+"]已经成功暂停。");
			}
			map.put("result", "success");
			map.put("message", "系统已经成功暂停定时任务！");
		} catch (Exception e) {
			map.put("result", "error");
			map.put("message", "暂停定时任务失败!");
			logger.error("暂停定时任务失败", e);
		}
		return map;
	}
	
	/**
	 * 根据ID恢复一个定时任务
	 * 返回JSON格式数据
	 * @param int id
	**/
	@RequestMapping( method = RequestMethod.GET, value = "/resumeJob/{id}" )
    @ResponseBody
    public Object resumeJob( @PathVariable("id") String id ){
		Sys_schedulejob schedulejob = null;
		Map<String, Object> map = new HashMap<String, Object>(), paramMap = new HashMap<String, Object>();
		try {
			TaskUtils taskUtils = new TaskUtils();
			 //先查询出需要操作的JOB对象			
			paramMap.put("jobid", id);
			schedulejob  = sys_schedulejobService.get(paramMap);
			if( schedulejob != null ){
				taskUtils.resumeJob( schedulejob );
				logger.debug("resumeJob方法定时任务：["+schedulejob.getJobname()+"]已经成功恢复。");
			}
			map.put("result", "success");
			map.put("message", "系统已经成功恢复定时任务！");
		} catch (Exception e) {
			map.put("result", "error");
			map.put("message", "恢复定时任务失败!");
			logger.error("恢复定时任务失败", e);
		}
		return map;
	}
	
	/**
	 * 根据ID执行一个定时任务
	 * 返回JSON格式数据
	 * @param int id
	**/
	@SuppressWarnings("static-access")
	@RequestMapping( method = RequestMethod.GET, value = "/runAJobNow/{id}" )
    @ResponseBody
    public Object runAJobNow( @PathVariable("id") String id ){
		Sys_schedulejob schedulejob = null;
		Map<String, Object> map = new HashMap<String, Object>(), paramMap = new HashMap<String, Object>();
		try {
			TaskUtils taskUtils = new TaskUtils();
			 //先查询出需要操作的JOB对象			
			paramMap.put("jobid", id);
			schedulejob = sys_schedulejobService.get(paramMap);
			if( schedulejob != null ){
				taskUtils.invokMethod( schedulejob, null );
				logger.debug("runAJobNow方法定时任务：["+schedulejob.getJobname()+"]已经成功运行。");
			}
			map.put("result", "success");
			map.put("message", "系统已经成功运行定时任务！");
		} catch (Exception e) {
			map.put("result", "error");
			map.put("message", "运行定时任务失败!");
			logger.error("系统异常", e);
		}
		return map;
	}	
}
